<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/Welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/goods' }">商品列表</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card class="box-card">
      <!-- 提示信息 -->
      <el-alert title="添加商品信息" type="info" show-icon center> </el-alert>
      <!--  步骤条 activeIndex-0 是给他转换为数字-->
      <el-steps
        :space="200"
        :active="activeIndex - 0"
        align-center
        finish-status="success"
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 纵向的步骤条 -->
      <el-form
        :model="addForm"
        :rules="addRules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
        label-position="top"
      >
        <!-- tab栏 :before-leave是当切换标签的时候是否要阻止-->
        <el-tabs
          tabPosition="left"
          v-model="activeIndex"
          :before-leave="beforeTabs"
          @tab-click="tabClick"
        >
          <el-tab-pane label="基本信息" name="0">
            <!-- 商品名称 -->
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <!-- 价格 -->
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <!-- 数量 -->
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <!-- 重量 -->
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="cateList"
                :props="cateProps"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!-- <el-tag :key="item.id" :type="item.id" effect="dark">
              {{}}
            </el-tag> -->
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyList"
              :key="item.attr_id"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  :label="items"
                  v-for="(items, i) in item.attr_vals"
                  :key="i"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="(item, i) in onlyList"
              :key="i"
            >
              <el-input v-model="item.attr_vals"> </el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!--action上传照片的接口
            on-preview文件上传完成时的钩子 on-remove文件移出时的钩子
            headers 设置请求头
              -->
            <el-upload
              class="upload-demo"
              action="http://timemeetyou.com:8889/api/private/v1/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headersObj"
              :on-success="handSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <!-- <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div> -->
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <el-button type="primary" @click="ADDClcik"> 添加商品 </el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片的预览 -->
    <el-dialog title="图片预览" :visible.sync="dialogVisible" width="50%">
      <img :src="previewPath" alt="" />
    </el-dialog>
  </div>
</template>
<script>
import http from '../../util/http'

export default {
  data () {
    return {
      // 步骤条的完成的索引
      activeIndex: '0',
      //   表单的数据
      addForm: {
        goods_name: '', // 商品名称
        goods_cat: [], // 分类列表
        goods_price: 0, // 价格
        goods_number: 0, // 数量
        goods_weight: 0, // 重量
        pics: [], // 图片
        goods_introduce: '' // 详情介绍
      },
      //   级联选择器的数据
      cateList: [],
      //   级联选择器的规则
      cateProps: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      },
      // 商品动态参数的数据
      manyList: [],
      // 商品的静态参数
      onlyList: [],
      // 设置上传图片的请求图
      headersObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 预览图片的地址
      previewPath: '',
      // 图片的预览弹框
      dialogVisible: false,
      // 验证规则
      addRules: {
        goods_name: [
          { required: true, message: '请输入商品信息！', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请选择商品分类！', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格！', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量！', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量！', trigger: 'blur' }
        ]
      }
    }
  },
  mounted () {
    this.getCateList()
  },
  methods: {
    //   获取分类的数据
    getCateList () {
      http('categories').then((res) => {
        this.cateList = res.data.data
      })
    },
    // 级联选择器选择完成要做的操作
    handleChange () {
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
      }
      //   console.log(this.addForm.goods_cat);
    },
    // 阻止切换其他栏
    beforeTabs (activeName, oldActiveName) {
      // activeName 即将要进入的
      // oldActiveName 要离开的
      if (oldActiveName === '0' && this.addForm.goods_cat.length !== 3) {
        this.$message.error('请选择商品分类！')
        return false
      }
    },
    // tab选中的时候触发
    tabClick () {
      // console.log(this.activeIndex);
      if (this.activeIndex === '1') {
        // console.log("动态参数");
        http({
          url: `categories/${this.addForm.goods_cat[2]}/attributes`,
          params: {
            sel: 'many'
          }
        }).then((res) => {
          // console.log(res.data.data);
          if (res.data.meta.status === 200) {
            this.$message.success('获取动态数据成功')
            res.data.data.forEach((item) => {
              item.attr_vals =
                item.attr_vals.length === 0 ? [] : item.attr_vals.split(',')
            })
            console.log(res.data.data)
            this.manyList = res.data.data
          }
        })
      }
      if (this.activeIndex === '2') {
        http({
          url: `categories/${this.addForm.goods_cat[2]}/attributes`,
          params: {
            sel: 'only'
          }
        }).then((res) => {
          console.log(res.data.data)
          if (res.data.meta.status === 200) {
            this.$message.success('获取静态数据成功')
            this.onlyList = res.data.data
          }
        })
      }
    },
    // 处理图片预览效果
    handlePreview (file) {
      // console.log(file);
      this.dialogVisible = true
      this.previewPath = file.response.data.url
    },
    // 处理移除图片的操作
    handleRemove (file) {
      // console.log(file);
      // 1获取图片的临时路径
      const files = file.response.data.tmp_path
      // 2在pics中找到图片的索引值
      const i = this.addForm.pics.findIndex((x) => {
        return x.pic === files
      })
      // 3利用splice的方法，把图片信息对象移出
      this.addForm.pics.splice(i, 1)
      console.log(this.addForm.pics)
    },
    // 图片上传成功
    handSuccess (response) {
      console.log(response)
      // 1拼接得到一个图片信息的图片
      const picInfo = { pic: response.data.tmp_path }
      // 2将图片信息的对象，push到PICS数组中
      this.addForm.pics.push(picInfo)
      console.log(this.addForm.pics)
    },
    // 确定添加
    ADDClcik () {
      // 把数组改为字符串
      this.addForm.goods_cat = this.addForm.goods_cat.join(',')
      console.log(this.addForm.goods_cat)
      http({
        url: 'goods',
        method: 'post',
        data: this.addForm
      }).then((res) => {
        // console.log(res.data);
        if (res.data.meta.status === 200) {
          this.$message.success('添加成功')
        } else {
          this.$message.error('添加失败')
        }
        this.$router.push('/goods')
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.el-steps {
  margin: 10px 0;
}
.el-button--primary {
  margin: 15px;
}
</style>
